package com.chinasofti.project.web;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import com.chinasofti.project.common.SimpleDigestUtil;
import com.chinasofti.project.common.pageQuery.PageResult;
import com.chinasofti.project.dal.model.BzShippingAddress;
import com.chinasofti.project.dal.model.BzUser;
import com.chinasofti.project.service.user.AddPaymentCodeService;
import com.chinasofti.project.service.user.ForgetThePasswordService;
import com.chinasofti.project.service.user.LineItemService;
import com.chinasofti.project.service.user.MoneyManageService;
import com.chinasofti.project.service.user.PersonalDataService;
import com.chinasofti.project.service.user.ShippingAddressService;
import com.chinasofti.project.service.user.info.LineItemInfo;
import com.chinasofti.project.service.user.result.MoneyManageResult;
import com.chinasofti.project.web.form.AddPaymentCodeForm;
import com.chinasofti.project.web.form.MoneyManageForm;
import com.chinasofti.project.web.form.PersonalDataForm;
import com.chinasofti.project.web.form.ShippingAddressForm;

@Controller
public class PersonalCenterController {
	
	@Autowired
	public PersonalDataService personalDataService;
	@Autowired
	public LineItemService lineItemService;
	@Autowired
	public ShippingAddressService shippingAddressService;
	@Autowired
	public MoneyManageService moneyManageService;
	@Autowired
	public AddPaymentCodeService addPaymentCodeService;
	@Autowired
	public ForgetThePasswordService forgetThePasswordService;
	@InitBinder
	public void initBinding(WebDataBinder wdb) {
		System.out.println("添加日期格式化器...");
		wdb.addCustomFormatter(new DateFormatter("yyyy-MM-dd"), Date.class);
	}
	
//	个人中心模块下的订单详情页
	@RequestMapping("toLineItem")
	public String toLineItem(){
		return "lineItem";
	}
	
	@RequestMapping("lineItem")
	public String LineItem(HttpSession session, HttpServletRequest request, ModelMap model) {
		int userId = (int) session.getAttribute("userId");
		// int userId = 1;
		long pageSize = 4;
		String pageIdxStr = request.getParameter("pageIdx");
		long pageIdx = getPageIdx(pageIdxStr);
		LineItemInfo lineItemInfo = new LineItemInfo(pageIdx, pageSize);
		lineItemInfo.setUserId(userId);
		PageResult a = lineItemService.displayTheOrder(lineItemInfo);

		model.put("orders", a.getResultList());
		model.put("pageIdx", pageIdx);
		model.put("totalCount", a.getTotalCount());
		model.put("totalPage", a.getTotalPage());
		return "lineItem";
	}
	
//	个人中心模块下的资金管理页面
	@RequestMapping("toMoneyManage")
	public String toMoneyManage(HttpSession session, ModelMap model) {
		int userId = (int) session.getAttribute("userId");
		// int userId = 1;
		BzUser user = moneyManageService.queryUser(userId);
		model.put("moneyManageUser", user);
		return "moneyManage";
	}
	
	@RequestMapping("moneyManage")
	public String moneyManage(MoneyManageForm moneyManageForm, HttpSession session, ModelMap model) {
		int userId = (int) session.getAttribute("userId");
		// int userId = 1;
		BzUser bzUser = new BzUser();
		BzUser moneyManageSqlUser = moneyManageService.queryUser(userId);
		if (moneyManageSqlUser.getUserPayPassword() == null || moneyManageSqlUser.getUserPayPassword() == "") {
			return "addPaymentCode";
		} else {
			bzUser.setUserId(userId);
			bzUser.setUserPayPassword(SimpleDigestUtil.encryptSHA(moneyManageForm.getUserPayPassword()));
			BigDecimal money = moneyManageForm.getUserBalance();
			MoneyManageResult m = moneyManageService.rechargeAmount(bzUser, money);
			if ("充值成功".equals(m)) {
				BzUser user = moneyManageService.queryUser(userId);
				model.put("moneyManageUser", user);
				return "moneyManage";
			} else {
				BzUser user = moneyManageService.queryUser(userId);
				model.put("moneyManageUser", user);
				return "moneyManage";
			}
		}

	}

//	个人中心模块下的个人资料页面
	@RequestMapping("toPersonalData")
	public String toPersonalDate(ModelMap model, HttpSession session) {
		int userId = (int) session.getAttribute("userId");
		// int userId = 11;
		BzUser sqluser = personalDataService.queryPersonalData(userId);
		model.put("sqluser", sqluser);
		return "personalData";
	}
	
	@RequestMapping("personalData")
	public String personalDate(PersonalDataForm personalDataForm, ModelMap model, HttpSession session) {
		int userId = (int) session.getAttribute("userId");
		// int userId = 11;
		BzUser user = new BzUser();
		BeanUtils.copyProperties(personalDataForm, user);
		user.setUserId(userId);
		if (personalDataForm == null) {
			BzUser sqluser = personalDataService.queryPersonalData(userId);
			model.put("sqluser", sqluser);
			return "personalData";
		} else {
			if (personalDataService.toPersonalDataService(user)) {
				BzUser sqluser = personalDataService.queryPersonalData(userId);
				model.put("sqluser", sqluser);
				session.setAttribute("user", sqluser);
				return "personalData";
			} else {
				model.put("personalDataErr", "修改资料失败");
				return "personalData";
			}
		}
	}

	// 添加收货地址页面
	@RequestMapping("shippingAddress")
	public String shippingAddress(ShippingAddressForm shippingAddressForm, HttpSession session, ModelMap model) {
		int userId = (int) session.getAttribute("userId");
		// int userId = 1;
		BzShippingAddress bzShippingAddress = new BzShippingAddress();
		bzShippingAddress.setUserId(userId);
		BeanUtils.copyProperties(shippingAddressForm, bzShippingAddress);
		if (bzShippingAddress.getSaReceiveName() == null && bzShippingAddress.getSaReceiveAddress() == null
				&& bzShippingAddress.getSaReceivePhone() == null) {
			List<BzShippingAddress> shippingAddressResult = shippingAddressService
					.ShippingAddressResult(bzShippingAddress);
			model.put("shippingAddressResult", shippingAddressResult);
			return "shippingAddress";
		} else {
			shippingAddressService.addShippingAddress(bzShippingAddress);
			List<BzShippingAddress> shippingAddressResult = shippingAddressService
					.ShippingAddressResult(bzShippingAddress);
			model.put("shippingAddressResult", shippingAddressResult);
			return "shippingAddress";
		}
	}

	// 个人中心模块下面的添加支付密码页面
	@RequestMapping("toAddPaymentCode")
	public String toAddPaymentCode() {
		return "addPaymentCode";
	}

	@RequestMapping("addPaymentCode")
	public String addPaymentCode(AddPaymentCodeForm addPaymentCodeForm,HttpSession session, ModelMap model) {
		int userId = (int) session.getAttribute("userId");
		// int userId = 11;
		BzUser sqlUser = addPaymentCodeService.verifyUser(userId);
		if (sqlUser.getUserPayPassword() == null || sqlUser.getUserPayPassword() == "") {
			if (!(addPaymentCodeForm.getReUserPayPassword().equals(addPaymentCodeForm.getUserPayPassword()))) {
				model.put("addPaymentCodeErr", "两次密码不一致");
				return "addPaymentCode";
			} else {
				BzUser user = new BzUser();
				user.setUserId(userId);
				user.setUserPayPassword(SimpleDigestUtil.encryptSHA(addPaymentCodeForm.getUserPayPassword()));
				addPaymentCodeService.setUserPayPassword(user);
				return "moneyManage";
			}
		} else {
			model.put("addPaymentCodeErr", "您已有支付密码");
			return "moneyManage";
		}
	}

	/**
	 * 修改密码三部曲
	 * 
	 * @return
	 */
	@RequestMapping("toModifyPassword")
	public String toForgetThePassword() {
		return "udai_modifypwd_step1";
	}

	@RequestMapping("modifyPassword1")
	public String forgetThePassword1(HttpServletRequest request, HttpSession session, ModelMap model) {
		int userId = (int) session.getAttribute("userId");
		// int userId = 1;
		String userPassword = SimpleDigestUtil.encryptSHA(request.getParameter("userPassword"));
		if (forgetThePasswordService.forgetThePassword1(userPassword, userId)) {
			System.out.println("udai_modifypwd_step2");
			return "udai_modifypwd_step2";
		} else {
			System.out.println("udai_modifypwd_step1");
			return "udai_modifypwd_step1";
		}
	}

	@RequestMapping("modifyPassword2")
	public String forgetThePassword2(HttpServletRequest request, HttpSession session, ModelMap model) {
		int userId = (int) session.getAttribute("userId");
		// int userId = 1;
		String newUserPassword = SimpleDigestUtil.encryptSHA(request.getParameter("newUserPassword"));
		String reNewUserPassword = SimpleDigestUtil.encryptSHA(request.getParameter("reNewUserPassword"));
		if (!(newUserPassword.equals(reNewUserPassword))) {
			model.put("modifyPassword2", "两次密码不一致");
			return "udai_modifypwd_step2";
		}

		if (forgetThePasswordService.forgetThePassword2(newUserPassword, userId)) {
			model.put("forgetThePassword2", "新密码不能为原密码");
			return "udai_modifypwd_step2";
		} else {
			BzUser bzUser = new BzUser();
			bzUser.setUserId(userId);
			bzUser.setUserPassword(newUserPassword);
			forgetThePasswordService.modifiUserPassword(bzUser);
			session.removeAttribute("user");
			session.removeAttribute("userId");
			session.invalidate();
			return "udai_modifypwd_step3";
		}

	}

	private long getPageIdx(String pageIdxStr) {
		return pageIdxStr == null || pageIdxStr == "" ? 1 : Integer.parseInt(pageIdxStr);
	}

}
